// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
				.length)));
	return fmt;
}


function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

var EARTH_RADIUS = 6378.137; //地球半径  
//将用角度表示的角转换为近似相等的用弧度表示的角 java Math.toRadians  
function rad(d) {
	return d * Math.PI / 180.0;
}
/** 
 * 谷歌地图计算两个坐标点的距离 
 * @param lng1  经度1 
 * @param lat1  纬度1 
 * @param lng2  经度2 
 * @param lat2  纬度2 
 * @return 距离（千米） 
 */
function getDisance(lat1, lng1, lat2, lng2) {
	var radLat1 = rad(lat1);
	var radLat2 = rad(lat2);
	var a = radLat1 - radLat2;
	var b = rad(lng1) - rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
		Math.cos(radLat1) * Math.cos(radLat2) *
		Math.pow(Math.sin(b / 2), 2)));
	s = s * EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000;
	return s;
}

module.exports = {
	formatTimeToStr: function(times, pattern) {
		try {
			if (times == undefined || times == '') {
				return '';
			} else {
				var d = times;

				if (times instanceof Date) {
					if (pattern) {
						d = times.Format(pattern);
					}
				} else {
					times = times.replace(/-/g, '/');
					times = times.replace(/T/g, ' ');
					//"2019-10-04T18:04:17"
					if (pattern) {
						//d = new Date(times).Format(pattern);
						d = new Date(times);
						d = d.Format(pattern);
					}
				}

				//times = times.replace('-','/');
				//times = times.replace(/-/g, '/');
				//var d2 = new Date(times);
				//var d = new Date(times).Format("yyyy-MM-dd hh:mm:ss");

				//if (pattern) {
				//d = new Date(times).Format(pattern);
				//	d = new Date(times);
				//	d = d.Format(pattern);
				//}
				//var time = d.replace(/\-/g, "/")
				return d;
			}
		} catch (e) {
			//TODO handle the exception
			return '';
		}
	},
	formatNumber: function(number, fixed) {
		try {
			if (number == undefined || number == '') {
				number = '0';
			}
			var num0 = new Number(number);
			var num = num0.toFixed(fixed);
			return num;
		} catch (e) {
			//TODO handle the exception
			return '0';
		}
	},
	formatDate: function(strData) {
		try {
			if (strData == undefined || strData == '') {
				return '';
			}
			var tmp = strData.toString();
			var seconds = tmp.replace(/\/Date\(/, "").replace(/\)\//, "");

			var nowt = Date(seconds);
			//var now = new Date(parseInt(seconds));
			//return now.asString("yyyy-mm-dd hh:ii:ss");

			var optime = new Date(nowt);

			if (optime instanceof Date) {
				return optime.Format("yyyy-MM-dd hh:mm:ss");
			} else {
				return '-';
			}
			//var str = nowt.toLocaleDateString();
			//return str;
		} catch (e) {
			//TODO handle the exception
			return '-';
		}
	},
	DiffNow: function(enDate) {
		if (enDate == '') {
			return 99;
		} else {
			try {
				enDate = enDate.replace(/-/g, '/');
				enDate = enDate.replace(/T/g, ' ');

				let sDate = Date()
				let eDate = Date.parse(enDate)
				sDate = Date.parse(sDate);

				//let def = (eDate - sDate)/1000;

				//const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000);

				//if (sDate > eDate) {
				//  return 0
				//}
				//if (sDate === eDate) {
				//  return 1
				//}
				const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000);
				return days;
			} catch (e) {
				return 99;
			}
		}
	},
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	getDisance: getDisance,
	GoUrl: function(url) {
		uni.navigateTo({
			url: url
		});
	},
	randomNum: function(minNum, maxNum) {
		//生成从minNum到maxNum的随机数
		switch (arguments.length) {
			case 1:
				return parseInt(Math.random() * minNum + 1, 10);
				break;
			case 2:
				return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
				break;
			default:
				return 0;
				break;
		}
	},
	GetColor: function(colorlist, index, sj) {
		var color;
		if (sj == 0) {
			if (colorlist != undefined && colorlist[index] != undefined) {
				color = colorlist[index];
			}
		} else {
			var num = colorlist.length;
			if (num > 0) {
				var _index = this.randomNum(0, num);
				color = colorlist[_index];
			}
		}
		return color;
	},

	//深拷贝
	deepClone(obj) {
		if (obj === null || typeof obj !== "object") {
			return obj;
		}
		//date类型
		if (obj instanceof Date) {
			const copydata = new Date();
			copydata.setTime(obj.getTime());
			return copydata
		}
		//正则
		if (obj instanceof RegExp) {
			const Constructor = obj.Constructor; //constructor 属性返回对创建此对象的数组函数的引用
			return new Constructor(obj)
		}
		if (obj instanceof Array || obj instanceof Object) { //数组以及引用类型
			const copyObj = Array.isArray(obj) ? [] : {}
			for (var i in obj) {
				copyObj[i] = typeof obj[i] == 'object' ? deepClone(obj[i]) : obj[i];
			}
			return copyObj;
		}
		return obj;
	}
}
